// VBConversions Note: VB project level imports
using System.Data;
using DevExpress.XtraEditors.Controls;
using System.Diagnostics;
using System.Xml.Linq;
using DevExpress.XtraEditors.Repository;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.VisualBasic;
using System.Configuration;
using System.Collections;
using DevExpress.XtraEditors;
using System.Data.Sql;
using Microsoft.SqlServer;
using System.Windows.Forms;
using System;
using DevExpress.XtraReports;
using Microsoft.SqlServer.Management.Smo;
using DevExpress;
using System.Linq;
using System.IO;
// End of VB project level imports

using System.Runtime.Serialization;

/// <summary>
/// Construit un DataSet a partir des Meta qui sont linker ensemble.
/// </summary>
/// <remarks>On pourrait mettre des MetaDataView a la place des Metadatatable...</remarks>
namespace SCIEF.SysBFW.CommonExt
{
	public class MetaDataSet : DataSet
	{
		
		public MetaDataSet()
		{
		}
		public MetaDataSet(string datasetName) : base(datasetName)
		{
		}
		public MetaDataSet(SerializationInfo info, StreamingContext context) : base(info, context)
		{
		}
		public MetaDataSet(SerializationInfo info, StreamingContext context, bool constructSchema) : base(info, context, constructSchema)
		{
		}
		
		private string _QueryName = null;
		public string QueryName
		{
			get
			{
				return _QueryName;
			}
			set
			{
				_QueryName = value;
			}
		}
		private Guid _ControlID = Guid.Empty;
		public Guid ControlID
		{
			get
			{
				return _ControlID;
			}
			set
			{
				_ControlID = value;
			}
		}
		private Guid _QueryID = Guid.Empty;
		public Guid QueryID
		{
			get
			{
				return _QueryID;
			}
			set
			{
				_QueryID = value;
			}
		}
		public string SQLWhere {get; set;}
		
		private MetaQuery mq;
		private MetaDataTable mainDataTable;
		
		public void FillDataSetByQueryName()
		{
			if (QueryName != null)
			{
				mq = MetaQuery.GetMetaQueryByName(QueryName);
				if (mq == null)
				{
					throw (new Exception(string.Format("MetaCommand for {0} does not exist", QueryName)));
				}
				else
				{
					InitData();
				}
			}
			else
			{
				throw (new Exception("Queryname must be initialize"));
			}
		}
		
		public void FillDataSetByControlID()
		{
			if (!ControlID.Equals(Guid.Empty))
			{
				mq = MetaQuery.GetMetaQueryByControlID(ControlID);
				if (mq == null)
				{
					throw (new Exception(string.Format("MetaCommand for MetaControl guid {0} does not exist", ControlID.ToString())));
				}
				else
				{
					QueryName = mq.QueryName;
					InitData();
				}
			}
			else
			{
				throw (new Exception("QueryID must be initialize"));
			}
		}
		
		public void FillDataSetByQueryID()
		{
			if (!QueryID.Equals(Guid.Empty))
			{
				mq = MetaQuery.GetMetaQueryById(QueryID);
				if (mq == null)
				{
					throw (new Exception(string.Format("MetaCommand for guid {0} does not exist", QueryID.ToString())));
				}
				else
				{
					QueryName = mq.QueryName;
					InitData();
				}
			}
			else
			{
				throw (new Exception("QueryID must be initialize"));
			}
		}
		
		public virtual void InitData()
		{
			string aChildRelationField = default(string);
			MetaQueryAccess DataViewAccess = default(MetaQueryAccess);
			DataRelation aDR = default(DataRelation);
			CommonExt.MetaDataTable metaDataTableChild = default(CommonExt.MetaDataTable);
			string childQuery;
			
			try
			{
				this.mainDataTable = new MetaDataTable();
				this.mainDataTable.QueryName = this.QueryName;
				if (!string.IsNullOrEmpty(this.SQLWhere))
				{
					this.mainDataTable.GetMetaCommand();
					if (!string.IsNullOrEmpty(this.mainDataTable.MetaCommand.SQLWhere))
					{
						this.mainDataTable.MetaCommand.SQLWhere += " AND ";
					}
					this.mainDataTable.MetaCommand.SQLWhere += string.Format(" {0}", this.SQLWhere);
				}
				else
				{
					this.mainDataTable.GetMetaCommand();
				}
				//TestPoint: Get the SqlStatement in immediate widow with, ?Me.MetaDataTable.MetaCommand.SQLStatement
				this.mainDataTable.FillBusinessApplicationData();
				//on assigne la meta Sécurity des MetaQuery définie par les MetaControls sur la dataview
				DataViewAccess = new MetaQueryAccess(mainDataTable.MetaCommand.MetaQuerieCD);
				//Testpoint: if security is not define properly in metacontrol the MetaQueryAccess always return FALSE for all of it's properties by design B.Desjardins 2012-05-16...
				mainDataTable.DefaultView.AllowNew = DataViewAccess.AllowCreate;
				mainDataTable.DefaultView.AllowEdit = DataViewAccess.AllowUpdate;
				mainDataTable.DefaultView.AllowDelete = DataViewAccess.AllowDelete;
				//oustanding: y reste le allowRead ,BD 2012-05-16
				
				this.Tables.Add(this.mainDataTable);
				foreach (DataRow row in this.mainDataTable.MetaCommand.GetChildDisplayQuery().Rows)
				{
					if (System.Convert.ToInt32(row["RelationOrder"]) >= 0)
					{
						childQuery = (string) (row["QueryName"].ToString());
						//aChildRelationField = String.Format("{0}_FK", row("ParentGUIDField").ToString)
						aChildRelationField = row["FKColumn_Name"].ToString();
						
						metaDataTableChild = new CommonExt.MetaDataTable() {QueryName = row["QueryName"].ToString()};
						//Ici on chaine nos WHERE Clause, pour que les enfants soit scopper sur le parent
						//
						metaDataTableChild.GetMetaCommand();
						DataViewAccess = new MetaQueryAccess((string) metaDataTableChild.MetaCommand.MetaQuerieCD);
						//if the control is define and you have access
						if (DataViewAccess.AllowRead == System.Convert.ToInt16(false))
						{
							metaDataTableChild.MetaCommand.SQLWhere = "1=2";
						}
						else
						{
							if (!string.IsNullOrEmpty(this.SQLWhere))
							{
								if (!string.IsNullOrEmpty((string) metaDataTableChild.MetaCommand.SQLWhere))
								{
									metaDataTableChild.MetaCommand.SQLWhere += " AND ";
								}
								metaDataTableChild.MetaCommand.SQLWhere += string.Format(" {0} IN ({1})", row["FKColumn_Name"].ToString(), this.mainDataTable.MetaCommand.GetSQLForSubSelect(row["PKColumn_Name"].ToString()));
							}
						}
						
						metaDataTableChild.FillBusinessApplicationData();
						metaDataTableChild.DefaultView.AllowNew = DataViewAccess.AllowCreate;
						metaDataTableChild.DefaultView.AllowEdit = DataViewAccess.AllowUpdate;
						metaDataTableChild.DefaultView.AllowDelete = DataViewAccess.AllowDelete;
						
						this.Tables.Add(metaDataTableChild);
						aDR = new DataRelation(row["Relation"].ToString(),
						this.Tables[row["ParentQueryName"].ToString()].Columns[row["PKColumn_Name"].ToString()],metaDataTableChild.Columns[aChildRelationField],	true);
						this.Relations.Add(aDR);
					}
				}
			}
			catch (Exception)
			{
				throw;
			}
		}
	}
	
}
